<template>
	<view class="page">
		<view class="cityBox">
			<hao-indexList v-if="letters.length > 0" :letters="letters" idValue="areaId" nameValue="areaName"
				@haoTap="onAddressClick" @haoChangeTab="changeTab" :currentCity="currentCity"
				:locationCity="locationCity" :hotCity="hotCity" @citySelected="handleCitySelected" :cityList="cityList"
				:cityTabs="cityTabs" :activeTab="activeTab"></hao-indexList>
		</view>
	</view>
</template>

<script setup>
	import haoIndexList from "@/components/hao-indexList/hao-indexList.vue";
	// 导入getCurrentInstance
	import {
		reactive,
		toRefs,
		onMounted,
		watch,
		getCurrentInstance
	} from 'vue';
	import {
		queryCityList,
		queryCityFromCode
	} from "@/api/common.js";
	import {
		useStore
	} from 'vuex';

	const store = useStore();
	// 使用导入的getCurrentInstance
	const instance = getCurrentInstance().proxy;
	const eventChannel = instance.getOpenerEventChannel();

	const state = reactive({
		activeTab: 0,
		letters: [],
		currentCity: {}, // 当前城市对象（从localStorage读取）
		locationCity: {},
		hotCity: [],
		cityList: {},
		cityTabs: [{
			name: '国内（含港澳台）',
			id: -1
		}],
		selectcityCode: '',
		selectedAreas: [],
		selectLocalStorage: {},
	});

	const {
		activeTab,
		letters,
		currentCity,
		locationCity,
		hotCity,
		cityList,
		cityTabs,
		selectedAreas,
		selectLocalStorage
	} = toRefs(state);

	// 监听本地存储变化，更新当前城市
	watch(selectLocalStorage, (newVal) => {
		if (newVal && newVal.cityName) {
			currentCity.value = {
				...newVal
			};
			updateCityTabs();
		}
	}, {
		deep: true
	});

	const onAddressClick = (item) => {
		console.log('item', item);
		if (!item.cityCode || !item.cityName) {
			console.log('错误：选择的城市数据不完整', item);
			return;
		}

		state.selectcityCode = item.cityCode;
		// 关键修复：根据层级动态生成areaName
		let areaName = '';
		if (item.hasOwnProperty('areaLevel')) {
			// 区县级：直接使用areaName
			areaName = item.areaName;
		} 
		console.log('areaName', areaName);
		const isExist = selectedAreas.value.some(area => area.cityCode === item.cityCode);
		if (!isExist) {
			selectedAreas.value.push({
				cityCode: item.cityCode,
				cityName: item.cityName,
				provinceName: item.provinceName,
				provinceCode: item.provinceCode,
				areaName: areaName|| '',
			});
		}

		const cityInfo = {
			cityCode: item.cityCode,
			cityName: item.cityName,
			areaId: item.areaId || item.cityCode,
			provinceName: item.provinceName || '',
			provinceCode: item.provinceCode || '',
			areaName: areaName || '', // Add areaName to the stored object
			areaLevel: item.areaLevel || (item.areaName?.includes('区') || item.areaName?.includes('县') ?
				'district' : 'city')
		};

		try {
			uni.setStorageSync('select_location', JSON.stringify(cityInfo));
			state.selectLocalStorage = {
				...cityInfo
			};
			currentCity.value = {
				...cityInfo
			};

			if (cityInfo.areaLevel === 'district') {
				returnSelectedData();
			} else {
				updateCityTabs();
				if (cityInfo.cityCode) {
					state.activeTab = 1;
					handleCitySelected(cityInfo);
				}
			}

		} catch (e) {
			console.log('存储失败', e);
		}
	};

	const returnSelectedData = () => {
		eventChannel.emit('acceptDataFromOpenedPage', {
			selectedAreas: selectedAreas.value.map(area => ({
				cityCode: area.cityCode,
				cityName: area.cityName,
				areaName: area.areaName || '',
				provinceName: area.provinceName,
				provinceCode: area.provinceCode,

			}))
		});
		if (state.selectcityCode) {
			uni.$emit('areaSelected', {
				areaId: state.selectcityCode
			});
		}

		uni.navigateBack();
	};

	// 在原有代码中找到updateCityTabs方法并替换
	const updateCityTabs = () => {
		// 重置tabs数组，保留国内选项
		cityTabs.value = [{
			name: '国内（含港澳台）',
			id: -1
		}];

		// 判断是否有选中的城市
		if (selectLocalStorage.value && selectLocalStorage.value.cityName) {
			const select = selectLocalStorage.value;
			let tabName = '';

			if (select.cityName.includes('市辖区')) {
				tabName = select.cityName.replace('市辖区', '') + '区县';
			} else if (select.cityName.endsWith('市')) {
				tabName = select.cityName.slice(0, -1) + '区县';
			} else {
				tabName = select.cityName + '区县';
			}

			const tabExists = cityTabs.value.some(tab => tab.name === tabName);
			if (!tabExists) {
				cityTabs.value.push({
					name: tabName,
					id: select.cityCode || select.areaId
				});
			}
		} else {
			// 未选择城市时添加默认区县Tab
			const defaultDistrictTab = {
				name: '区/县',
				id: 0 // 使用特殊ID标识默认状态
			};
			// 检查是否已存在默认Tab，避免重复添加
			const tabExists = cityTabs.value.some(tab => tab.id === 0);
			if (!tabExists) {
				cityTabs.value.push(defaultDistrictTab);
			}
		}
	};

	const fetchCityList = async () => {
		const locationStr = uni.getStorageSync('current_location'); // 读取current_location
		const params = {};

		if (locationStr) {
			try {
				const location = JSON.parse(locationStr);
				if (location.latitude && location.longitude) {
					params.latitude = location.latitude;
					params.longitude = location.longitude;
				}
				// 从current_location中提取cityName设置为当前城市
				if (location.cityName) {
					currentCity.value = {
						cityName: location.cityName,
						isLocation: true // 标记为定位城市
					};
				}
			} catch (e) {
				console.log('解析位置信息失败', e);
			}
		}

		try {
			const res = await queryCityList(params);
			if (res.code === 200) {
				cityList.value = res.data.cityList;
				letters.value = res.data.letters;
				hotCity.value = res.data.hotCity;
			}
		} catch (err) {
			console.log('获取城市列表失败', err);
		} finally {
			uni.hideLoading();
		}
	};

	const changeTab = async (id) => {
		if (id === -1) {
			state.activeTab = 0;
			await fetchCityList();
		} else {
			state.activeTab = 1;
			const cityId = selectLocalStorage.value.cityCode || selectLocalStorage.value.areaId;

			if (cityId) {
				try {
					const res = await queryCityFromCode({
						cityCode: cityId
					});
					if (res.code === 200) {
						hotCity.value = res.data;
					}
				} catch (err) {
					console.log('获取区县数据失败', err);
				}
			}
		}
	};

	const handleCitySelected = async (city) => {
		state.selectLocalStorage = {
			...city
		};
		updateCityTabs();

		if (city.cityCode) {
			state.activeTab = 1;
			try {
				const res = await queryCityFromCode({
					cityCode: city.cityCode
				});
				if (res.code === 200) {
					hotCity.value = res.data;
				}
			} catch (err) {
				console.log('获取区县数据失败', err);
			}
		}
	};

	onMounted(() => {
		try {
			// 优先从select_location获取已选城市
			const selectedLocation = uni.getStorageSync('select_location');
			if (selectedLocation) {
				state.selectLocalStorage = JSON.parse(selectedLocation);
				currentCity.value = {
					...state.selectLocalStorage
				};
			}

			// 从current_location读取定位城市
			const currentLocation = uni.getStorageSync('current_location');
			if (currentLocation) {
				const location = JSON.parse(currentLocation);
				if (location.cityName) {
					locationCity.value = {
						cityName: location.cityName,
						isLocation: true
					};
				}
			}
			updateCityTabs();
		} catch (e) {
			console.log('初始化数据失败', e);
		}

		uni.showLoading({
			title: '获取数据中'
		});
		fetchCityList();

		eventChannel.on('acceptDataFromOpenerPage', (data) => {
			if (data && data.selectedAreas) {
				selectedAreas.value = data.selectedAreas;
			}
		});
	});
</script>

<style>
	.uni-indexed-list__menu {
		position: absolute;
		right: 0;
	}
</style>
<style lang="scss" scoped>
	.page {
		background: #f5f5f5;
	}

	.titleBox {
		padding: 41rpx 24rpx 0;
		background: #ffffff;

		.search {
			height: 72rpx;
		}

		.titleTabs {
			margin-top: 26rpx;

			.tab {
				font-weight: 400;
				font-size: 30rpx;
				color: #666666;
				margin-right: 40rpx;
				padding-bottom: 26rpx;
				position: relative;

				&.active {
					font-weight: 600;
					color: #333333;
				}

				&.active::after {
					content: "";
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					display: block;
					width: 47rpx;
					height: 8rpx;
					background: #2f80ed;
					border-radius: 4rpx;
				}
			}
		}
	}

	.cityBox {
		.currentCity {
			font-weight: 600;
			font-size: 30rpx;
			color: #333333;
			margin-top: 30rpx;
			padding: 0 24rpx;
		}

		.hotCitys {
			margin-top: 40rpx;

			.hotCity {
				font-weight: 400;
				font-size: 26rpx;
				color: #666666;
			}
		}

		.address-list {
			position: relative;
			margin-top: 20rpx;
			height: 100vh;
		}
	}
</style>